//
//  ImportTool.swift
//  XingCeHelper
//
//  Created by 申铭 on 2022/10/11.
//

import Foundation
import CoreXLSX
import SVProgressHUD

class ImportTool {
    
    /// 导入成语
    static func importIdiom(completion: ((Bool) -> Void)? = nil) {
        DispatchQueue.global().async {
            guard let path = Bundle.main.url(forResource: "成语", withExtension: "txt") else {
                DispatchQueue.main.async {
                    print("路径错误")
                    completion?(false)
                }
                return
            }
            
            do {
                let data = try Data(contentsOf: path)
                let text = String(data: data, encoding: .utf8) ?? ""
                let strs = text.split(separator: "\n")
                var results = [ImportResult]()
                for str in strs {
                    if let result = IdiomStore.saveOrUpdate(str: String(str)) {
                        results.append(result)
                    }
                }
                
                Global.shared.importResults = results
                
                DispatchQueue.main.async {
                    completion?(true)
                }
            } catch {
                DispatchQueue.main.async {
                    completion?(false)
                    print("data转换出错：\(error)")
                }
            }
        }
        
    }
    
    /// 导入成语
    /// - Parameter string: 字符串
    static func importIdiom(string: String) {
        let strs = string.split(separator: "\n")
        for str in strs {
            IdiomStore.saveOrUpdate(str: String(str))
        }
        
        ImportResultController().push()
    }
    
    /// 程序解析excel
    static func importShenLun(data: Data) {
        do {
            let file = try XLSXFile(data: data)
            let wbks = try file.parseWorkbooks()
            let sharedStrings = try file.parseSharedStrings()
            for wbk in wbks {
                for (name, path) in try file.parseWorksheetPathsAndNames(workbook: wbk) {
                    if let worksheetName = name {
                        print("This worksheet has a name: \(worksheetName)")
                    }

                    let worksheet = try file.parseWorksheet(at: path)
                    parseShenLunRows(worksheet.data?.rows ?? [], sharedStrings: sharedStrings)
                }
            }
        } catch {
            print("parseWorkbooks 出错")
        }
    }
    
    /// 导入规范用词
    /// 程序解析excel
    static func importShenLun() {
        guard let path = Bundle.main.path(forResource: "申论规范用词", ofType: "xlsx") else {
            print("路径为空")
            return
        }
        
        guard let file = XLSXFile(filepath: path) else {
            print("XLSX file at \(path) is corrupted or does not exist")
            return
        }
        
        do {
            let wbks = try file.parseWorkbooks()
            let sharedStrings = try file.parseSharedStrings()
            for wbk in wbks {
                for (name, path) in try file.parseWorksheetPathsAndNames(workbook: wbk) {
                    if let worksheetName = name {
                        print("This worksheet has a name: \(worksheetName)")
                    }

                    let worksheet = try file.parseWorksheet(at: path)
                    parseShenLunRows(worksheet.data?.rows ?? [], sharedStrings: sharedStrings)
                }
            }
        } catch {
            print("parseWorkbooks 出错")
        }
    }
    
    /// 问题对策
    static func importShenLun2(data: Data) {
        do {
            let file = try XLSXFile(data: data)
            let wbks = try file.parseWorkbooks()
            let sharedStrings = try file.parseSharedStrings()
            for wbk in wbks {
                for (name, path) in try file.parseWorksheetPathsAndNames(workbook: wbk) {
                    if let worksheetName = name {
                        print("This worksheet has a name: \(worksheetName)")
                    }

                    let worksheet = try file.parseWorksheet(at: path)
                    parseShenLun2Rows(worksheet.data?.rows ?? [], sharedStrings: sharedStrings)
                }
            }
        } catch {
            print("parseWorkbooks 出错")
        }
    }
    
    /// 导入问题对策
    static func importShenLun2() {
        guard let path = Bundle.main.path(forResource: "申论问题对策总结", ofType: "xlsx") else {
            print("路径为空")
            return
        }
        
        guard let file = XLSXFile(filepath: path) else {
            print("XLSX file at \(path) is corrupted or does not exist")
            return
        }
        
        do {
            let wbks = try file.parseWorkbooks()
            let sharedStrings = try file.parseSharedStrings()
            for wbk in wbks {
                for (name, path) in try file.parseWorksheetPathsAndNames(workbook: wbk) {
                    if let worksheetName = name {
                        print("This worksheet has a name: \(worksheetName)")
                    }

                    let worksheet = try file.parseWorksheet(at: path)
                    parseShenLun2Rows(worksheet.data?.rows ?? [], sharedStrings: sharedStrings)
                }
            }
        } catch {
            print("parseWorkbooks 出错")
        }
    }
    
    // MARK: - private
    
    private static func parseShenLun2Rows(_ rows: [Row], sharedStrings: SharedStrings?) {
        var specifications = [SpecificationModel]()
        
        for row in rows {
            if var specifi = parseShenLun2Row(row, sharedStrings: sharedStrings) {
                if specifi.originalText == nil { continue }
                specifi.category = "无"
                specifi.type = .issuesAndMeasure
                specifications.append(specifi)
            }
        }
        SpecificationStore.saveOrUpdate(specifications: specifications)
    }
    
    private static func parseShenLun2Row(_ row: Row, sharedStrings: SharedStrings?) -> SpecificationModel? {
        var specification = SpecificationModel()
        
        for c in row.cells {
            if c.type == .sharedString {
                guard let sharedStr = sharedStrings else {
                    print("sharedStrings为空")
                    return nil
                }
                
                let str = c.stringValue(sharedStr) ?? "无"
                if c.styleIndex == 1 { // 标题
                    print("sharedStrings为标题")
                } else {
                    if c.reference.column.value == "A" { // 材料原文
                        specification.originalText = str
                    } else if c.reference.column.value == "B" { // 问题
                        specification.specificationText = str
                    } else if c.reference.column.value == "C" { // 对策
                        specification.measureText = str
                    }
                }
            } else {
                print("不是字符串")
            }
        }
        
        return specification
    }
    
    private static func parseShenLunRows(_ rows: [Row], sharedStrings: SharedStrings?) {
        var specifications = [SpecificationModel]()
        var category: String?
        
        for row in rows {
            if var specifi = parseShenLunRow(row, sharedStrings: sharedStrings) {
                if let tCategory = specifi.category {
                    category = tCategory
                }
                
                if specifi.originalText == nil || specifi.specificationText == nil {
                    continue
                }
                
                specifi.type = .summarize
                specifi.category = category
                specifications.append(specifi)
            }
        }
        SpecificationStore.saveOrUpdate(specifications: specifications)
    }
    
    /// 解析规范用词的每一行
    /// - Parameters:
    ///   - row: 行
    ///   - sharedStrings: sharedStrings
    private static func parseShenLunRow(_ row: Row, sharedStrings: SharedStrings?) -> SpecificationModel? {
        var specification = SpecificationModel()
        
        for c in row.cells {
            if c.type == .sharedString {
                guard let sharedStr = sharedStrings else {
                    print("sharedStrings为空")
                    return nil
                }
                
                let str = c.stringValue(sharedStr) ?? "无"
                if c.styleIndex == 1 { // 标题
                } else if c.styleIndex == 2 { // 分类
                    specification.category = str
                } else {
                    if c.reference.column.value == "A" { // 材料原文
                        specification.originalText = str
                    } else if c.reference.column.value == "B" { // 规范表达
                        specification.specificationText = str
                    }
                }
            } else {
                print("不是字符串")
            }
        }
        
        return specification
    }
    
}
